module.exports = app => {
  const xml = require('xml2js')
  const cache = require("memory-cache");
  const createHash = require('create-hash')
  const route = require("express").Router({
    mergeParams: true
  });
  const common = require("./../../util/common");
  const wxConfig = require("../../config").wx;
  const util = require("../../util/util");
  const UserModel = require("../../models/User.js");
  const UserIntegral = require("../../models/UserIntegral")
  const ServiceModel = require("./../../models/ServiceProduct.js")
  const OrderSku = require("./../../models/OrderSku.js")
  const ShoppingCart = require("./../../models/ShoppingCart.js")
  const UserAddress = require("./../../models/UserAddress")
  //https://open.weixin.qq.com/connect/oauth2/authorize?
  //appid=wxf0e81c3bee622d60&redirect_uri=http%3A%2F%2Fnba.bluewebgame.com%2Foauth_response.php&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
  route.get("/getopenid", (req, res) => {
    const url = req.query.url;
    cache.put("redirectUrl", url);
    const redirectUri = "http://wx.pipipi.net/api/wx/redirect";
    res.redirect(
      `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${wxConfig.appId}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
    );
  });
  route.get("/redirect", async (req, res) => {
    const code = req.query.code;
    //{"access_token":"30_UI5TG8x_ihBLa6bE19iozwGuwhJJXUrV07cuwt5CY-uGolqDiZPCbwQeGubGS-WMuhShXesFu0FL34Cwiwe4WQ","expires_in":7200,
    //"refresh_token":"30_5T9znfvbnZt7ZdcW5dMG6qw2FHmc5FmZMIDHbG1fHpHGXm7hK7MgWVfS3XtS7gPbSRPzhK8TMFlA4JMZLDAdtg","openid":"o2BqVt4ZsLaXY_vrCGSFX2WqOXC0","scope":"snsapi_userinfo"}
    if (!code) {
      util.handleFail("code不存在");
    } else {
      const data = await common.getAccessToken(code);
      const openid = data.data.openid;
      const accessToken = data.data.access_token;
      const url = cache.get("redirectUrl");
      let expire_time = 1000 * 60 * 60 * 2;
      let user = await UserModel.findOne({
        openId: openid
      })
      if (!user) {
        user = await UserModel.create({
          openId: openid
        });
        UserIntegral.create({
          userId: user._id,
          count: 1000
        })
      }else{
        UserIntegral.findByIdAndUpdate({
          userId:user._id
        },{count:1000})
      }
      console.log('userid:--------', user._id)
      const userInfo = await common.getUserInfo(accessToken, openid);
      res.cookie("userInfo", JSON.stringify({ ...userInfo.data, user: user['_doc'] }), {
        maxAge: expire_time
      });
      res.redirect(url);
      // res.json(util.handleSuc(userInfurlo.data))
    }
  });
  route.get("/jssdk", async (req, res) => {
    const url = req.query.url
    let comToken = cache.get('comToken')
    let ticket = cache.get('ticket')
    if (!comToken) {
      const data = await common.getCommonToken()
      console.log('token', data)
      if (data.code == 0) {
        comToken = data.data['access_token']
        cache.put('comToken', comToken, 7200 * 1000)
      }
    }
    if (!ticket) {
      const data = await common.getTicket(comToken)
      if (data.code == 0) {
        ticket = data.data['ticket']
        cache.put('ticket', ticket, 7200 * 1000)
      }
    }
    let params = {
      noncestr: util.createNonceStr(),
      jsapi_ticket: ticket,
      timestamp: util.createTimeStamp(),
      url
    }
    let string1 = ''
    Object.keys(params).sort().forEach(item => {
      string1 += '&' + item + '=' + params[item]
    })
    let string2 = string1.substr(1)
    const sign = createHash('sha1').update(string2).digest('hex')
    res.json(util.handleSuc({
      appId: wxConfig.appId,
      timestamp: params.timestamp,
      noncestr: params.noncestr,
      signature: sign,
      jsApiList: ['chooseWXPay', 'openAddress','updateTimelineShareData']
    }))
  })
  route.post('/orderSku', async (req, res) => {
    const skuList = req.body.skuList;
    const openid = req.body.openId;
    const userid = req.body.userId;
    const address = req.body.address;
    const orderId = req.body.orderId;
    console.log(skuList)
    if (openid) {
      //appid, body, nonce_str, notify_url, openid, out_trade_no, spbill_create_ip, total_fee
      let total_fee = skuList.reduce((total, sku) => {
        return total + sku.product.price * sku.count
      }, 0)
      let skuParam = skuList.map(sku => {
        return { product: sku.product._id, count: sku.count }
      })
      let payParams = {
        appid: wxConfig.appId,
        nonce_str: util.createNonceStr(),
        notify_url: 'http://wx.pipipi.net/pay/callback',
        openid,
        out_trade_no: util.randerOrderNum(),
        spbill_create_ip: '47.99.118.233',
        total_fee: total_fee * 100
      }
      if (orderId) {
        payParams.out_trade_no = orderId
      }
      payParams.body = '致❤Time订单：' + payParams.out_trade_no
      payParams.sign = common.getPaySign(payParams.appid, payParams.body, payParams.nonce_str, payParams.notify_url, payParams.openid, payParams.out_trade_no, payParams.spbill_create_ip, payParams.total_fee)
      const pay = common.getOrderParams(payParams.appid, payParams.body, payParams.nonce_str, payParams.notify_url, payParams.openid, payParams.out_trade_no, payParams.spbill_create_ip, payParams.total_fee, payParams.sign)
      const data = await common.UnifiedOrder(pay)
      if (data) {
        const options = {
          populate: 'products.product'
        }
        
        if (!orderId) {
          let addressObj = await UserAddress.create({
            ...address,
            userId: userid
          })
          let order = await OrderSku.create({
            userid,
            orderId: payParams.out_trade_no,
            products: skuParam,
            openid: payParams.openid,
            address: addressObj._id
          })
          order = await OrderSku.findById(order._id).setOptions(options)
          res.json(util.handleSuc({ data, order }))
        } else {
          let order = await OrderSku.find({ orderId })
          res.json(util.handleSuc({ data, order }))
        }
      } else {
        res.json(util.handleFail('下单失败'))
      }

    } else {
      res.json(util.handleFail('请先登录', 400))
    }
  })
  app.use("/api/wx", route);
  app.post("/pay/callback", (req, res) => {
    xml.parseString(req.rawBody.toString("utf-8"), async (error, xmlData) => {
      if (error) {
        console.log('callback Err', error)
        res.send("fail")
        return;
      }
      const data = xmlData.xml;
      const RESULT_CODE = data.result_code[0];
      console.log('result_code', RESULT_CODE)
      if (RESULT_CODE == 'SUCCESS') {
        const orderId = data.out_trade_no[0];
        let orderObj = await OrderSku.findOneAndUpdate({
          orderId
        }, {
          status: 1
        }, { new: true })
        console.log('orderObj', orderObj)
        if (orderObj) {
          let data = '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
          res.send(data);
        }
      } else {
        res.send('fail')
      }
    })
  })
  //抽奖接口
  app.post("/api/common/lottery", async (req, res) => {
    const userid = req.body.user
    console.log('userid', userid)
    const user = await UserModel.findOne({
      _id: userid
    })
    if (!user) {
      res.json(util.handleFail('不存在该用户'))
    }
    let integral = await UserIntegral.findOne({
      userId: userid
    })
    if (integral.count < 10) {
      res.json(util.handleFail('积分不足'))
    } else {
      integral = await UserIntegral.findOneAndUpdate({
        userId: userid
      }, { "$inc": { "count": -10 } }, { new: true })
      res.json(util.handleSuc({ draw: '爱奇艺VIP月卡', integral }))
    }
  })
  app.post('/api/common/addcart', async (req, res) => {
    const body = req.body
    let shoppingCart = await ShoppingCart.findOneAndUpdate(body, { "$inc": { "count": + 1 } }, { new: true })
    if (shoppingCart) {
      res.json(util.handleSuc(shoppingCart))
    } else {
      shoppingCart = await ShoppingCart.create(body)
      res.json(util.handleSuc(shoppingCart))
    }
  })
  app.delete('/api/common/cart', async (req, res) => {
    const cart = req.query.cart
    const deleteRes = await ShoppingCart.deleteMany({ _id: { $in: cart } })
    res.json(util.handleSuc(deleteRes))
  })
};
